package com.example.dbcms.config;

import com.example.dbcms.domain.User;
import com.example.dbcms.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> stringSet = new HashSet<>();
        stringSet.add("user:show");
        stringSet.add("user:admin");
        info.setStringPermissions(stringSet);
        return info;
    }

    /**
     * 进行登录信息验证
     * private UserService userService;
     * <p>
     * 获取即将需要认证的信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        System.out.println("-------身份认证方法--------");
        String userAccount = (String) authenticationToken.getPrincipal();//获取账号
        String userPwd = new String((char[]) authenticationToken.getCredentials());//获取密码
        User user = userService.getUserByUserAccount(userAccount);
        if(null!=user){
            if(!user.getPassword().equals(userPwd)) {
                throw new AccountException("密码错误");
            }
        }else {
            throw new AccountException("没有此用户");
        }
        return new SimpleAuthenticationInfo(userAccount, userPwd, getName());
    }
}
